"""
des: 
author: 邵宁
date: 2022-09-10
"""
import os
import time
import sqlite3
import subprocess
from util import path


def cmd_run(cmd_str, log_path=""):
    print("将要执行的命令：", cmd_str)
    print("日志保存目录：", log_path)
    # res_status = subprocess.run([cmd_str], shell=True, stdout=subprocess.STDOUT, stderr=subprocess.STDOUT)
    log_path = os.path.join(log_path, "log_" + time.strftime("%H%M%S"))
    path.dir_init(log_path)
    f = open(log_path, "w", encoding="utf=-8")
    res = subprocess.run(cmd_str, shell=True, stdout=f, stderr=f)
    f.close()
    with open(log_path, "r", encoding="utf-8") as f:
        log_str = f.read()
    res_json = {
        "status": str(res.returncode),
        "log_file_path": log_path,
        "log": log_str
    }
    # res_status = os.popen(cmd_str)
    # res_status = os.system(cmd_str)
    return res_json


def get_db():
    db = sqlite3.connect(os.path.join("util", 'database.db'))
    return db


def deal_insert(sql):
    db_conn = get_db()
    cursor = db_conn.cursor()
    cursor.execute(sql)
    db_conn.commit()
    db_conn.close()


def deal_insert_try(sql):
    try:
        deal_insert(sql)
        return True
    except Exception as e:
        return False


def update_session_status(session_token, session_status):
    sql = f"UPDATE table_session SET session_status='{session_status}' WHERE session_token='{session_token}'"
    deal_insert(sql)


def update_session_info(session_token, session_info):
    sql = f"UPDATE table_session SET session_info='{session_info}' WHERE session_token='{session_token}'"
    deal_insert(sql)
